package my.mall.front.api.service

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import my.mall.common.annotation.Slf4j
import my.mall.common.enums.RespMetaEnum
import my.mall.common.pojo.CommonResp
import my.mall.common.util.DateUtils.asDate
import my.mall.common.util.JwtUtils.createToken
import my.mall.common.util.RespUtils.success
import my.mall.common.util.RespUtils.warning
import my.mall.db.entity.User
import my.mall.db.mapper.UserMapper
import my.mall.front.api.enums.UserStatus
import org.springframework.stereotype.Service
import java.time.LocalDateTime
import java.util.*

@Slf4j
@Service
class UserService(
    private val userMapper: UserMapper
) {

    fun login(phoneNum: Long?, code: Int): CommonResp<*> {
        val user = userMapper.selectOne(
            QueryWrapper<User>()
                .select(
                    User.ID,
                    User.SMS_CODE,
                    User.SMS_TIME,
                    User.USER_STATUS
                )
                .eq(User.PHONE_NUM, phoneNum)
        )
        if (user == null || UserStatus.NORMAL.code != user.userStatus) {
            return warning<Any>(RespMetaEnum.NOT_AUTH)
        }
        if (user.smsCode == null || user.smsTime == null || code != user.smsCode) {
            return warning(400, "验证码错误")
        }
        if (user.smsTime!!.isBefore(LocalDateTime.now().minusMinutes(5))) {
            return warning(400, "获取验证码超时，请重新获取")
        }
        val expireTime = LocalDateTime.now().plusDays(2)
        val token = createToken(user.id, asDate(expireTime))
        return success(Collections.singletonMap("token", token))
    }
}
